<!--个人信息-->
<template>
  <div id="personCenterPage">
    <a-tabs
      class="custom-tabs"
      v-model:activeKey="activeKey"
      tab-position="left"
      size="large"
      style="margin-left: 500px"
    >
      <a-tab-pane key="1" tab="个人资料">
        <h2>基本信息</h2>
        <a-divider />
        <a-form
          :model="formState"
          name="basic"
          label-align="left"
          autocomplete="off"
          class="custom-form"
        >
          <a-form-item label="用户头像">
            <div class="avatar-upload-container">
              <a-avatar :size="80" :src="formState.userAvatar || defaultAvatar" />
              <a-upload
                name="avatar"
                :show-upload-list="false"
                :before-upload="beforeAvatarUpload"
                @change="handleAvatarChange"
              >
                <a-button type="primary" style="margin-left: 16px">更换头像</a-button>
              </a-upload>
            </div>
          </a-form-item>
          <a-form-item label="用户账号" name="userAccount">
            <div class="input-wrapper">
              <a-input
                class="fixed-width-input"
                v-model:value="formState.userAccount"
                placeholder="请输入账号"
                disabled
              />
            </div>
          </a-form-item>
          <a-form-item label="用户昵称" name="userName">
            <div
              class="input-wrapper"
              @mouseenter="handleMouseEnter('userName')"
              @mouseleave="handleMouseLeave('userName')"
            >
              <a-input
                class="fixed-width-input"
                v-model:value="formState.userName"
                placeholder="未填写"
                :disabled="!editState.userName"
              />
              <a-button
                v-if="!editState.userName"
                type="link"
                class="edit-button"
                :icon="h(FormOutlined)"
                v-show="hoverState.userName"
                @click="startEdit('userName')"
              >
                编辑
              </a-button>
              <a-button
                v-else
                type="primary"
                size="small"
                @click="saveUserInfo('userName')"
                style="margin-right: 8px"
              >
                保存
              </a-button>
              <a-button
                v-if="editState.userName"
                type="default"
                size="small"
                @click="cancelEdit('userName')"
              >
                取消
              </a-button>
            </div>
          </a-form-item>
          <a-form-item label="个人简介" name="userProfile">
            <div
              class="input-wrapper"
              @mouseenter="handleMouseEnter('userProfile')"
              @mouseleave="handleMouseLeave('userProfile')"
            >
              <a-textarea
                class="fixed-width-input"
                v-model:value="formState.userProfile"
                placeholder="未填写"
                :rows="4"
                :disabled="!editState.userProfile"
              />
              <a-button
                v-if="!editState.userProfile"
                type="link"
                class="edit-button"
                :icon="h(FormOutlined)"
                v-show="hoverState.userProfile"
                @click="startEdit('userProfile')"
              >
                编辑
              </a-button>
              <div v-else class="action-buttons">
                <a-button
                  type="primary"
                  size="small"
                  @click="saveUserInfo('userProfile')"
                  style="margin-right: 8px"
                >
                  保存
                </a-button>
                <a-button type="default" size="small" @click="cancelEdit('userProfile')">
                  取消
                </a-button>
              </div>
            </div>
          </a-form-item>
        </a-form>
      </a-tab-pane>
      <a-tab-pane key="2" tab="账号设置">
        <div v-if="!showCancelAccount && !showSetPassword">
          <h2>账号设置</h2>
          <a-row style="margin-top: 20px">
            <a-col :span="12" style="font-size: 16px">修改密码</a-col>
            <a-col :span="12">
              <a-button type="link" size="large" @click="showSetPasswordPage">设置密码</a-button>
            </a-col>
          </a-row>
          <a-divider />
          <a-row>
            <a-col :span="12" style="font-size: 16px">账号注销</a-col>
            <a-col :span="12">
              <a-button type="link" size="large" @click="showCancelAccountPage">确认注销</a-button>
            </a-col>
          </a-row>
        </div>

        <div v-else-if="showCancelAccount">
          <div class="breadcrumb-nav">
            <a-breadcrumb>
              <a-breadcrumb-item>
                <a @click="backToAccountSettings">账号设置</a>
              </a-breadcrumb-item>
              <a-breadcrumb-item>账号注销</a-breadcrumb-item>
            </a-breadcrumb>
          </div>
          <div class="account-delete-container">
            <div class="rules-section">
              <div class="rules-content">
                <h3>账号注销删除规则为您主动放弃以下资产和权益，且同意以下规则：</h3>
                <ol>
                  <li>账号注销后，您将无法登录、使用云图库账号，且不支持找回任何个人资料。</li>
                  <li>该账号将解除与其他产品的绑定或授权关系，且不支持找回。</li>
                  <li>VIP会员等付费权益，包含已经产生但未消耗完毕的权益或未来预期权益。</li>
                  <li>将不再支持使用已注销账号的用户ID注册新的账号。</li>
                  <li>注销云图库账号并不代表您注销前的账号行为和相关责任得到豁免或减轻。</li>
                </ol>
              </div>
            </div>
            <div class="action-section">
              <a-button type="primary" danger @click="handleCancelAccount">
                已知晓，确认注销
              </a-button>
            </div>
          </div>
        </div>

        <div v-else>
          <div class="breadcrumb-nav">
            <a-breadcrumb>
              <a-breadcrumb-item>
                <a @click="backToAccountSettings">账号设置</a>
              </a-breadcrumb-item>
              <a-breadcrumb-item>账号注销</a-breadcrumb-item>
            </a-breadcrumb>
          </div>
          <div class="account-delete-container">
            <div class="setting-password-container">
              <a-form
                :model="passwordForm"
                name="passwordForm"
                label-align="left"
                autocomplete="off"
                @finish="handleUpdatePassword"
                :rules="passwordRules"
              >
                <a-form-item name="oldPassword" label="输入旧密码">
                  <a-input-password
                    class="fixed-width-input"
                    v-model:value="passwordForm.oldPassword"
                    placeholder="请输入旧密码"
                  >
                    <template #prefix>
                      <LockOutlined style="color: rgba(0, 0, 0, 0.25)" />
                    </template>
                  </a-input-password>
                </a-form-item>
                <a-form-item name="newPassword" label="输入新密码">
                  <a-input-password
                    class="fixed-width-input"
                    v-model:value="passwordForm.newPassword"
                    placeholder="请输入新密码"
                  >
                    <template #prefix>
                      <LockOutlined style="color: rgba(0, 0, 0, 0.25)" />
                    </template>
                  </a-input-password>
                </a-form-item>
                <a-form-item name="confirmPassword" label="确认新密码">
                  <a-input-password
                    class="fixed-width-input"
                    v-model:value="passwordForm.confirmPassword"
                    placeholder="请确认新密码"
                  >
                    <template #prefix>
                      <LockOutlined style="color: rgba(0, 0, 0, 0.25)" />
                    </template>
                  </a-input-password>
                </a-form-item>
                <a-form-item>
                  <a-button type="primary" html-type="submit" style="margin-left: 100px"
                    >更新密码
                  </a-button>
                </a-form-item>
              </a-form>
            </div>
          </div>
        </div>
      </a-tab-pane>
    </a-tabs>
    <!-- 注销账号确认弹窗 -->
    <a-modal
      v-model:visible="cancelAccountModalVisible"
      title="注销账号"
      @ok="handleCancelAccountConfirm"
      @cancel="handleCancel"
      :okButtonProps="{ danger: true, loading: submitting }"
      okText="确认注销"
      cancelText="取消"
    >
      <p>注销账号后，您的所有数据将被永久删除且无法恢复。请输入密码确认操作：</p>
      <a-form :model="cancelAccountForm" layout="vertical">
        <a-form-item
          name="userPassword"
          :rules="[
            { required: true, message: '请输入密码' },
            { min: 8, message: '密码不能小于 8 位' },
          ]"
        >
          <a-input-password
            v-model:value="cancelAccountForm.userPassword"
            placeholder="请输入用户密码"
          />
        </a-form-item>
      </a-form>
    </a-modal>
    <!-- 操作结果提示 -->
    <a-modal
      v-model:visible="resultModalVisible"
      :title="resultModalTitle"
      :closable="false"
      :footer="null"
    >
      <div class="result-modal-content">
        <a-result :status="resultStatus" :title="resultTitle" :sub-title="resultSubTitle">
          <template #extra>
            <a-button type="primary" @click="handleResultModalClose">确定</a-button>
          </template>
        </a-result>
      </div>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref, h, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import { FormOutlined, LockOutlined } from '@ant-design/icons-vue'
import { useLoginUserStore } from '@/stores/useLoginUserStore.ts'
import {
  getUserByIdUsingGet,
  userCancelAccountUsingPost,
  userEditPasswordUsingPost,
} from '@/api/userController.ts'
import { useRouter } from 'vue-router'

// 默认头像
const defaultAvatar = 'https://gw.alipayobjects.com/zos/rmsportal/BiazfanxmamNRoxxVxka.png'

const router = useRouter()

// 是否显示注销账号页面
const showCancelAccount = ref(false)
const showSetPassword = ref(false)

const loginUserStore = useLoginUserStore()
const loginUserInfo = loginUserStore.loginUser
const cancelAccountModalVisible = ref(false)
const submitting = ref(false)

const activeKey = ref('1')

const formState = reactive({
  userName: '',
  userProfile: '',
  userAvatar: '',
  userAccount: '',
})

// 密码表单
const passwordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: '',
})

// 密码表单验证规则
const passwordRules = {
  oldPassword: [
    { required: true, message: '请输入当前密码' },
    { min: 8, message: '密码不能小于 8 位' },
  ],
  newPassword: [
    { required: true, message: '请输入新密码' },
    { min: 8, message: '密码不能小于 8 位' },
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码' },
    { min: 8, message: '密码不能小于 8 位' },
    {
      validator: async (rule: any, value: string) => {
        if (value !== passwordForm.newPassword) {
          return Promise.reject('两次输入的密码不一致')
        }
        return Promise.resolve()
      },
    },
  ],
}

const cancelAccountForm = reactive({
  userName: '',
  userPassword: '',
})

// 编辑状态
const editState = reactive({
  userName: false,
  userProfile: false,
})

// 原始数据备份，用于取消编辑
const originalData = reactive({
  userName: '',
  userProfile: '',
})

// 结果弹窗状态
const resultModalVisible = ref(false)
const resultModalTitle = ref('')
const resultStatus = ref<'success' | 'error' | 'info'>('info')
const resultTitle = ref('')
const resultSubTitle = ref('')

// 在组件挂载时获取用户信息
onMounted(async () => {
  await fetchUserInfo()
})

// 显示注销账号页面
const showCancelAccountPage = () => {
  showCancelAccount.value = true
}
const showSetPasswordPage = () => {
  showSetPassword.value = true
}

// 返回账号设置页面
const backToAccountSettings = () => {
  showCancelAccount.value = false
  showSetPassword.value = false
}

// 获取用户信息
const fetchUserInfo = async () => {
  if (loginUserInfo.id !== undefined) {
    try {
      const res = await getUserByIdUsingGet({ id: loginUserInfo.id })
      if (res.data.code === 0 && res.data.data) {
        const userData = res.data.data
        formState.userAccount = String(userData.userAccount || '')
        formState.userName = String(userData.userName || '')
        formState.userProfile = String(userData.userProfile || '')
        formState.userAvatar = String(userData.userAvatar || defaultAvatar)
        // 备份原始数据
        originalData.userName = formState.userName
        originalData.userProfile = formState.userProfile
      }
    } catch (error) {
      message.error('获取用户信息失败')
      console.error('获取用户信息失败:', error)
    }
  }
}

// 开始编辑
const startEdit = (field: keyof typeof editState) => {
  editState[field] = true
}

// 取消编辑
const cancelEdit = (field: keyof typeof editState) => {
  editState[field] = false
  // 恢复原始数据
  formState[field] = originalData[field]
}

// 保存用户信息
const saveUserInfo = async (field: keyof typeof editState) => {
  try {
    const updateData = {
      [field]: formState[field],
    }

    //todo: 调用更新用户信息接口
    /*  const res = await updateUserUsingPost(updateData)
      if (res.data.code === 0) {
        message.success(`${field === 'userName' ? '用户昵称' : '个人简介'}更新成功`)
        // 更新原始数据
        originalData[field] = formState[field]
        // 更新登录用户信息
        if (field === 'userName') {
          // loginUserStore.updateUserName(formState.userName)
        }
        editState[field] = false
      } else {
        message.error(res.data.message || '更新失败')
      }*/
  } catch (error) {
    message.error('更新失败')
    console.error('更新失败:', error)
  }
}

// 头像上传前的校验
const beforeAvatarUpload = (file: File) => {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
  if (!isJpgOrPng) {
    message.error('只能上传JPG或PNG格式的图片!')
  }
  const isLt2M = file.size / 1024 / 1024 < 2
  if (!isLt2M) {
    message.error('图片大小不能超过2MB!')
  }
  return isJpgOrPng && isLt2M
}

// 处理头像上传
const handleAvatarChange = async (info: any) => {
  if (info.file.status === 'uploading') {
    return
  }
  if (info.file.status === 'done') {
    // 获取上传后的头像URL
    const avatarUrl = info.file.response.data
    // 更新用户头像
    try {
      const updateData = {
        userAvatar: avatarUrl,
      }
      //todo: 调用更新头像接口
      /*const res = await updateUserUsingPost(updateData)
      if (res.data.code === 0) {
        message.success('头像更新成功')
        formState.userAvatar = avatarUrl
        // 更新登录用户信息
        loginUserStore.updateUserAvatar(avatarUrl)
      } else {
        message.error(res.data.message || '头像更新失败')
      }*/
    } catch (error) {
      message.error('头像更新失败')
      console.error('头像更新失败:', error)
    }
  }
}

// 处理密码更新
const handleUpdatePassword = async () => {
  if (passwordForm.newPassword !== passwordForm.confirmPassword) {
    message.error('两次输入的密码不一致')
    return
  }

  try {
    submitting.value = true
    const updateData = {
      userPassword: passwordForm.oldPassword,
      newPassword: passwordForm.newPassword,
    }
    const res = await userEditPasswordUsingPost(updateData)
    if (res.data.code === 0) {
      // 显示成功结果
      resultStatus.value = 'success'
      resultModalTitle.value = '密码修改成功'
      resultTitle.value = '密码已成功更新'
      resultSubTitle.value = '请使用新密码登录系统'
      resultModalVisible.value = true
      // 清空表单
      passwordForm.oldPassword = ''
      passwordForm.newPassword = ''
      passwordForm.confirmPassword = ''
      // 退出登录
      await loginUserStore.userLogout()
      /* setTimeout(() => {
         loginUserStore.logout()
         router.push('/login')
       }, 2000)*/
    } else {
      message.error(res.data.message || '密码更新失败')
    }
  } catch (error) {
    message.error('密码更新失败')
    console.error('密码更新失败:', error)
  } finally {
    submitting.value = false
  }
}

// 处理注销账号
const handleCancelAccount = () => {
  cancelAccountModalVisible.value = true
  // cancelAccountForm.id = loginUserInfo.id
}

// 确认注销账号
const handleCancelAccountConfirm = async () => {
  if (!cancelAccountForm.userPassword) {
    message.error('请输入密码')
    return
  }

  try {
    submitting.value = true
    const deleteData = {
      userPassword: cancelAccountForm.userPassword,
    }
    const res = await userCancelAccountUsingPost(deleteData)
    if (res.data.code === 0) {
      cancelAccountModalVisible.value = false
      // 显示成功结果
      resultStatus.value = 'success'
      resultModalTitle.value = '账号注销成功'
      resultTitle.value = '您的账号已成功注销'
      resultSubTitle.value = '感谢您使用我们的服务'
      resultModalVisible.value = true

      // 退出登录

      await router.push({
        path: '/',
        replace: true,
      })
      /*setTimeout(() => {
        loginUserStore.logout()
        router.push('/user/login')
      }, 100)*/
    } else {
      message.error(res.data.message || '账号注销失败')
    }
  } catch (error) {
    message.error('账号注销失败')
    console.error('账号注销失败:', error)
  } finally {
    submitting.value = false
  }
}

// 取消注销账号
const handleCancel = () => {
  cancelAccountModalVisible.value = false
  cancelAccountForm.userPassword = ''
}

// 关闭结果弹窗
const handleResultModalClose = () => {
  resultModalVisible.value = false
}

// 悬浮状态
const hoverState = reactive({
  userAvatar: false,
  userName: false,
  userProfile: false,
})

// 定义 hoverState 的键类型
type HoverStateKeys = keyof typeof hoverState

// 处理鼠标悬浮事件
const handleMouseEnter = (field: HoverStateKeys) => {
  hoverState[field] = true
}

// 处理鼠标离开事件
const handleMouseLeave = (field: HoverStateKeys) => {
  hoverState[field] = false
}
</script>

<style scoped>
/* 自定义标签页样式 */
.custom-tabs {
  width: 1200px; /* 设置整个标签页组件的总宽度 */
  margin: 0 auto; /* 居中显示 */
}

/* 控制右侧内容区域的宽度 */
.custom-tabs :deep(.ant-tabs-content-holder) {
  width: 800px; /* 设置右侧内容区域的宽度 */
  padding: 0 20px; /* 添加内边距 */
}

#personCenterPage :deep(.ant-tabs-tab) {
  height: 50px !important;
}

/* 隐藏表单边框 */
.custom-form :deep(.ant-form-item) {
  border: none;
  margin-bottom: 16px;
}

/* 隐藏输入框边框 */
.custom-form :deep(.ant-input) {
  border: none !important; /* 强制隐藏边框 */
  box-shadow: none !important; /* 隐藏聚焦时的阴影 */
}

/* 输入框容器 */
.input-wrapper {
  position: relative;
  display: flex;
  align-items: center;
}

/* 固定输入框宽度 */
.fixed-width-input {
  width: 300px; /* 固定宽度 */
}

/* 修改按钮样式 */
.edit-button {
  margin-left: 8px;
  opacity: 0;
  transition: opacity 0.3s ease;
}

/* 悬浮时显示按钮 */
.input-wrapper:hover .edit-button {
  opacity: 1;
}

.breadcrumb-nav {
  margin-bottom: 20px;
}

.account-delete-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

.rules-section {
  margin-bottom: 30px;
}

.rules-section h3 {
  font-size: 18px;
  margin-bottom: 16px;
  color: #333;
}

.rules-content {
  background-color: #f5f5f5;
  padding: 20px;
  border-radius: 4px;
}

.rules-content p {
  margin-bottom: 16px;
  color: #666;
}

.rules-content ol {
  padding-left: 20px;
}

.rules-content li {
  margin-bottom: 12px;
  line-height: 1.5;
  color: #666;
}

.action-section {
  text-align: center;
  margin-top: 30px;
}

.action-section button {
  min-width: 120px;
  height: 40px;
  font-size: 16px;
}
</style>
